package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONObject;
import com.hy.corecode.idgen.WFGIdGenerator;
import io.xxx.xbutler.data.RobotJoinRoomRecordMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.RobotJoinRoomRecord;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 禁止入群回调
 * <p>
 * 机器人被好友邀请入群时，因风控原因禁止入群，通过此接口回调；
 * 每类型风控原因禁止入群对应一种风控识别码，具体对应关系如下：
 * 200101：今日入群已达上限
 * 200102：邀请人来自黑名单
 * 200103：三天内该群的入群机器人已达上限 （三天内同一个群（40人以上）禁止2个以上同一商户机器人入群，5个以上平台机器人入群）
 * 200104：该用户邀请入群已达上限
 * 120502：机器人8天内被踢3次
 * 200106：检测到该群存在违规行为或内容
 * 200107：该群为企业外部群，今日入群次数已达上限，无法入群
 * 121401：机器人本周接口调用天数已超出上限
 * 200110：连续调用天数已超出上限
 *
 * <pre>
 * {
 *     "nType": 4513,
 *     "vcMerchantNo": "",
 *     "vcRobotWxId": "",
 *     "vcRobotSerialNo": "",
 *     "vcSerialNo": "",
 *     "nResult": 1,
 *     "vcResult": "",
 *     "Data": {
 *         "vcChatRoomName": "",
 *         "vcChatRoomBase64Name": "",
 *         "vcInviterWxId": "",
 *         "vcInviterSerialNo": "",
 *         "nRiskTypeCode": "",
 *         "vcRiskTypeDesc": "",
 *         "vcLimitTime": "2021-04-30 00:00:00"
 *     },
 *     "nTimeStamp": 1619685864087
 * }
 * </pre>
 */
@Slf4j
@Component
public class _4513Handler implements CallbackHandler {

    @Resource
    private WFGIdGenerator idGenerator;

    @Resource
    private RobotJoinRoomRecordMapper robotJoinRoomRecordMapper;

    @Override
    public String name() {
        return "禁止入群回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 4513;
    }

    @Override
    public void handle(Callback callback) {
        JSONObject data = (JSONObject) callback.getData();
        RobotJoinRoomRecord record = new RobotJoinRoomRecord()
                .setId(idGenerator.next())
                .setRobotId(callback.getRobotId())
                .setRobotSerialNo(callback.getRobotSerialNo())
                .setRoomName(data.getString("vcChatRoomName"))
                .setBase64RoomName(data.getString("vcChatRoomBase64Name"))
                .setInviterId(data.getString("vcInviterWxId"))
                .setInviterSerialNo(data.getString("vcInviterSerialNo"))
                .setRiskCode(data.getString("nRiskTypeCode"))
                .setRiskReason(data.getString("vcRiskTypeDesc"))
                .setCreatedTime(LocalDateTime.now());
        Instant limitTime = data.getInstant("vcLimitTime");
        if (limitTime != null) {
            record.setLimitTime(LocalDateTime.ofInstant(limitTime, ZoneId.systemDefault()));
        }
        robotJoinRoomRecordMapper.insert(record);
    }
}
